import { EUploadConditionType, IUploadCondition, IImageProp } from '@/types'
export function resetImagesStyle(
  image: IImageProp | undefined,
  width: number,
  height?: number,
  format: string[] = ['m_pad']
) {
  if (image && image.url) {
    const formatStr = format.reduce((prev, current) => current + ',' + prev, '')
    image.fitUrl = `${image.url}?x-oss-process=image/resize,${formatStr}`
    if (height) {
      image.fitUrl += `h_${height}`
    }
    image.fitUrl += `,w_${width}`
  } else {
    image = {
      fitUrl: require('@/assets/default.jpeg')
    }
  }
  return image
}

export function beforeUploadCheck(file: File, condition: IUploadCondition) {
  const { size, format } = condition
  let error: EUploadConditionType = EUploadConditionType.EMPTY
  const isValidFormat = format ? format.includes(file.type) : true
  const isValidSize = size ? file.size / (1024 * 1024) < size : true
  if (!isValidFormat) {
    error = EUploadConditionType.FORMAT
  } else if (!isValidSize) {
    error = EUploadConditionType.SIZE
  }
  return {
    passed: isValidFormat && isValidSize,
    error
  }
}

export function arrToObj<T extends { _id?: string }>(arr: Array<T>) {
  return arr.reduce((prev, current) => {
    if (current._id) {
      prev[current._id] = current
    }
    return prev
  }, {} as { [key: string]: T })
}

export function objToArr<T>(obj: { [key: string]: T }): T[] {
  const arr = Object.values(obj)
  return arr
}
